package com.alex.wechat.mp.message.mass.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.UUID;

import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.oConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.message.mass.entity.WxMassBillEntity;
import com.alex.wechat.mp.message.mass.entity.WxMassUsersEntity;
import com.alex.wechat.mp.message.mass.service.WxMassBillServiceI;
import com.gomore.jeecg.common.Assert;
import com.gomore.jeecg.util.BillNumberGenerator;

@Service("wxMassBillService")
@Transactional
public class WxMassBillServiceImpl extends CommonServiceImpl implements WxMassBillServiceI {

  public <T> void delete(T entity) {
    super.delete(entity);
    // 执行删除操作配置的sql增强
    this.doDelSql((WxMassBillEntity) entity);
  }

  @Override
  public <T> Serializable save(T entity) {
    if (entity != null && (entity instanceof WxMassBillEntity)) {
      WxMassBillEntity bill = (WxMassBillEntity) entity;
      bill.setAccountId(WxContext.getOriginalId());
      try {
        bill.setBillNumber(
            BillNumberGenerator.nextBillNumber(WxMassBillEntity.class.getSimpleName()));
      } catch (Exception e) {
        throw new BusinessException(e);
      }
    }
    return super.save(entity);
  }

  public void addMain(WxMassBillEntity wxMassBill, List<WxMassUsersEntity> wxMassUsersList) {
    if (wxMassBill != null) {
      wxMassBill.setAccountId(WxContext.getOriginalId());
    }

    // 保存主信息
    this.save(wxMassBill);

    /** 保存-微信群发用户 */
    for (WxMassUsersEntity wxMassUsers : wxMassUsersList) {
      // 外键设置
      wxMassUsers.setOwner(wxMassBill.getId());
      this.save(wxMassUsers);
    }
    // 执行新增操作配置的sql增强
    this.doAddSql(wxMassBill);
  }

  public void updateMain(WxMassBillEntity wxMassBill, List<WxMassUsersEntity> wxMassUsersList) {
    // 保存主表信息
    this.saveOrUpdate(wxMassBill);
    // ===================================================================================
    // 获取参数
    // ===================================================================================
    // 1.查询出数据库的明细数据-微信群发用户
    String hql0 = "from WxMassUsersEntity where 1 = 1 AND oWNER = ? ";
    List<WxMassUsersEntity> wxMassUsersOldList = this.findByHql(hql0, wxMassBill.getId());
    // 2.筛选更新明细数据-微信群发用户
    if (wxMassUsersList != null && wxMassUsersList.size() > 0) {
      for (WxMassUsersEntity oldE : wxMassUsersOldList) {
        boolean isUpdate = false;
        for (WxMassUsersEntity sendE : wxMassUsersList) {
          // 需要更新的明细数据-微信群发用户
          if (oldE.getId().equals(sendE.getId())) {
            try {
              MyBeanUtils.copyBeanNotNull2Bean(sendE, oldE);
              this.saveOrUpdate(oldE);
            } catch (Exception e) {
              e.printStackTrace();
              throw new BusinessException(e.getMessage());
            }
            isUpdate = true;
            break;
          }
        }
        if (!isUpdate) {
          // 如果数据库存在的明细，前台没有传递过来则是删除-微信群发用户
          super.delete(oldE);
        }

      }
      // 3.持久化新增的数据-微信群发用户
      for (WxMassUsersEntity wxMassUsers : wxMassUsersList) {
        if (oConvertUtils.isEmpty(wxMassUsers.getId())) {
          // 外键设置
          wxMassUsers.setOwner(wxMassBill.getId());
          this.save(wxMassUsers);
        }
      }
    }
    // 执行更新操作配置的sql增强
    this.doUpdateSql(wxMassBill);
  }

  public void delMain(WxMassBillEntity wxMassBill) {
    // 删除主表信息
    this.delete(wxMassBill);
    // ===================================================================================
    // 获取参数
    // ===================================================================================
    // 删除-微信群发用户
    String hql0 = "from WxMassUsersEntity where 1 = 1 AND oWNER = ? ";
    List<WxMassUsersEntity> wxMassUsersOldList = this.findByHql(hql0, wxMassBill.getId());
    this.deleteAllEntitie(wxMassUsersOldList);
  }

  /**
   * 默认按钮-sql增强-新增操作
   * 
   * @param id
   * @return
   */
  public boolean doAddSql(WxMassBillEntity t) {
    return true;
  }

  /**
   * 默认按钮-sql增强-更新操作
   * 
   * @param id
   * @return
   */
  public boolean doUpdateSql(WxMassBillEntity t) {
    return true;
  }

  /**
   * 默认按钮-sql增强-删除操作
   * 
   * @param id
   * @return
   */
  public boolean doDelSql(WxMassBillEntity t) {
    return true;
  }

  /**
   * 替换sql中的变量
   * 
   * @param sql
   * @return
   */
  public String replaceVal(String sql, WxMassBillEntity t) {
    sql = sql.replace("#{id}", String.valueOf(t.getId()));
    sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
    sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
    sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
    sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
    sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
    sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
    sql = sql.replace("#{sys_org_code}", String.valueOf(t.getSysOrgCode()));
    sql = sql.replace("#{sys_company_code}", String.valueOf(t.getSysCompanyCode()));
    sql = sql.replace("#{bill_number}", String.valueOf(t.getBillNumber()));
    sql = sql.replace("#{msg_type}", String.valueOf(t.getMsgType()));
    sql = sql.replace("#{text_msg}", String.valueOf(t.getTextMsg()));
    sql = sql.replace("#{template_id}", String.valueOf(t.getTemplateId()));
    sql = sql.replace("#{media_id}", String.valueOf(t.getMediaId()));
    sql = sql.replace("#{is_to_all}", String.valueOf(t.getIsToAll()));
    sql = sql.replace("#{send_ignore_reprint}", String.valueOf(t.getSendIgnoreReprint()));
    sql = sql.replace("#{card_id}", String.valueOf(t.getCardId()));
    sql = sql.replace("#{card_name}", String.valueOf(t.getCardName()));
    sql = sql.replace("#{msg_id}", String.valueOf(t.getMsgId()));
    sql = sql.replace("#{msg_data_id}", String.valueOf(t.getMsgDataId()));
    sql = sql.replace("#{send_status}", String.valueOf(t.getSendStatus()));
    sql = sql.replace("#{send_err_msg}", String.valueOf(t.getSendErrMsg()));
    sql = sql.replace("#{total_count}", String.valueOf(t.getTotalCount()));
    sql = sql.replace("#{filter_count}", String.valueOf(t.getFilterCount()));
    sql = sql.replace("#{sent_count}", String.valueOf(t.getSentCount()));
    sql = sql.replace("#{error_count}", String.valueOf(t.getErrorCount()));
    sql = sql.replace("#{check_state}", String.valueOf(t.getCheckState()));
    sql = sql.replace("#{remark}", String.valueOf(t.getRemark()));
    sql = sql.replace("#{template_name}", String.valueOf(t.getTemplateName()));
    sql = sql.replace("#{accountid}", String.valueOf(t.getAccountId()));
    sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
    return sql;
  }

  @Override
  @Transactional(readOnly = true)
  public WxMassBillEntity getByMsgId(String msgId) {
    Assert.assertArgumentNotEmpty(msgId, "msgId");
    return findUniqueByProperty(WxMassBillEntity.class, "msgId", msgId);
  }

  @Override
  public List<String> getUsers(String billId) {
    Assert.assertArgumentNotEmpty(billId, "billId");
    String hql = "select fansOpenId from " + WxMassUsersEntity.class.getName() + " where owner = ?";
    return findByHql(hql, billId);
  }
}